<template>
  <div v-if="props.show" class="modal-overlay" @click.self="$emit('close')">
    <div class="modal-content">
      <div class="modal-header">
        <h3>资料库用户管理</h3>
        <button class="close-btn" @click="$emit('close')">&times;</button>
      </div>
      <div class="modal-body">
        <div class="permissions-container">
          <!-- 所有用户窗口 -->
          <div v-if="showAllUsers" class="permission-section">
            <h4>所有用户</h4>
            <div  class="search-box">
              <input 
                type="text" 
                v-model="allUsersSearchQuery" 
                placeholder="搜索用户..." 
                class="search-input"
              />
            </div>
            <div v-if="showAllUsers" class="user-list">
              <div 
                v-for="user in filteredAllUsers" 
                :key="user.id"
                class="user-item"
              >
                <span class="user-name">{{ user.nickname }}</span>
                <button 
                  class="action-btn" 
                  @click="addUserToCurrentGroup(user.id)"
                  v-if="currentGroupType"
                >
                  添加到{{ {
                    'admin': '管理员',
                    'viewer': '可查看用户',
                    'editor': '可编辑用户',
                    'assigner': '可分配权限用户'
                  }[currentGroupType] }}
                </button>
              </div>
              <div v-if="filteredAllUsers.length === 0" class="empty-list">
                没有用户
              </div>
            </div>
          </div>
          <!-- 管理员列表 - 仅超级管理员可见 -->
          <div class="permission-section" v-if="(isAdmin && (!showAllUsers || currentGroupType === 'admin'))">
            <h4>
              管理员列表
              <button class="add-btn" @click="setCurrentGroupType('admin')">
                {{ currentGroupType === 'admin' && showAllUsers ? '确定' : '添加用户' }}
              </button>
            </h4>
            <div class="search-box">
              <input 
                type="text" 
                v-model="adminSearchQuery" 
                placeholder="搜索管理员..." 
                class="search-input"
              />
            </div>
            <div class="user-list">
              <div 
                v-for="user in filteredAdminUsers" 
                :key="user.id"
                class="user-item"
                :class="{ 'selected': selectedAdminUsers.includes(user.id) }"
                @click="toggleUserSelection(user.id, 'admin')"
              >
                <span class="user-name">{{ user.nickname }}</span>
                <span class="user-role">{{ user.roleName }}</span>
                <button 
                 v-if="showAllUsers"
                  class="remove-btn" 
                  @click.stop="removeUserFromGroup(user.id, 'admin')"
                >
                  移除
                </button>
              </div>
              <div v-if="filteredAdminUsers.length === 0" class="empty-list">
                没有管理员
              </div>
            </div>
          </div>
          
          <!-- 可查看用户列表 - 所有角色都可见 -->
          <div class="permission-section" v-if="!showAllUsers || currentGroupType === 'viewer'">
            <h4>
              可查看用户列表
              <button v-if="(isAdmin || isAdvancedLibraryAdmin || isAssignRole)" class="add-btn" @click="setCurrentGroupType('viewer')">
                {{ currentGroupType === 'viewer' && showAllUsers ? '确定' : '添加用户' }}
              </button>
            </h4>
            <div class="search-box">
              <input 
                type="text" 
                v-model="viewerSearchQuery" 
                placeholder="搜索可查看用户..." 
                class="search-input"
              />
            </div>
            <div class="user-list">
              <div 
                v-for="user in filteredViewerUsers" 
                :key="user.id"
                class="user-item"
                :class="{ 'selected': selectedViewerUsers.includes(user.id) }"
                @click="toggleUserSelection(user.id, 'viewer')"
              >
                <span class="user-name">{{ user.nickname }}</span>
                <span class="user-role">查看者</span>
                <button 
                 v-if="showAllUsers"
                  class="remove-btn" 
                  @click.stop="removeUserFromGroup(user.id, 'viewer')"
                >
                  移除
                </button>
              </div>
              <div v-if="filteredViewerUsers.length === 0" class="empty-list">
                没有可查看用户
              </div>
            </div>
          </div>
          
          <!-- 可编辑用户列表 - 仅超级管理员和高级资料库管理员可见 -->
          <div class="permission-section" v-if="((isAdmin || isAdvancedLibraryAdmin || isAssignRole) && (!showAllUsers || currentGroupType === 'editor'))">
            <h4>
              可编辑用户列表
              <button v-if="(isAdmin || isAdvancedLibraryAdmin || isAssignRole)" class="add-btn" @click="setCurrentGroupType('editor')">
                {{ currentGroupType === 'editor' && showAllUsers ? '确定' : '添加用户' }}
              </button>
            </h4>
            <div class="search-box">
              <input 
                type="text" 
                v-model="editorSearchQuery" 
                placeholder="搜索可编辑用户..." 
                class="search-input"
              />
            </div>
            <div class="user-list">
              <div 
                v-for="user in filteredEditorUsers" 
                :key="user.id"
                class="user-item"
                :class="{ 'selected': selectedEditorUsers.includes(user.id) }"
                @click="toggleUserSelection(user.id, 'editor')"
              >
                <span class="user-name">{{ user.nickname }}</span>
                <span class="user-role">编辑者</span>
                <button 
                  v-if="showAllUsers"
                  class="remove-btn" 
                  @click.stop="removeUserFromGroup(user.id, 'assigner')"
                >
                  移除
                </button>
              </div>
              <div v-if="filteredEditorUsers.length === 0" class="empty-list">
                没有可编辑用户
              </div>
            </div>
          </div>
          
          <!-- 可分配权限用户列表 - 仅超级管理员可见 -->
          <div class="permission-section" v-if="((isAdmin || isAdvancedLibraryAdmin) && (!showAllUsers || currentGroupType === 'assigner'))">
            <h4>
              可分配权限用户列表
              <button v-if="(isAdmin || isAdvancedLibraryAdmin)" class="add-btn" @click="setCurrentGroupType('assigner')">
                {{ currentGroupType === 'assigner' && showAllUsers ? '确定' : '添加用户' }}
              </button>
            </h4>
            <div class="search-box">
              <input 
                type="text" 
                v-model="assignerSearchQuery" 
                placeholder="搜索可分配权限用户..." 
                class="search-input"
              />
            </div>
            <div class="user-list">
              <div 
                v-for="user in filteredAssignerUsers" 
                :key="user.id"
                class="user-item"
                :class="{ 'selected': selectedAssignerUsers.includes(user.id) }"
                @click="toggleUserSelection(user.id, 'assigner')"
              >
                <span class="user-name">{{ user.nickname }}</span>
                <span class="user-role">权限分配者</span>
                <button 
                  v-if="showAllUsers"
                  class="remove-btn" 
                  @click.stop="removeUserFromGroup(user.id, 'assigner')"
                >
                  移除
                </button>
              </div>
              <div v-if="filteredAssignerUsers.length === 0" class="empty-list">
                没有可分配权限用户
              </div>
            </div>
          </div>
        </div>
      </div>

    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, Ref } from 'vue';
import { API_CONFIG } from '../../config/apiConfig';
import { User,KnowledgeBaseGroupUserRsp } from '../../types';
import { ToastService } from '../../utils/toastService';

// 获取当前登录用户信息
const userInfoStr = localStorage.getItem('userInfo');
const currentUser = ref<User | null>(userInfoStr ? JSON.parse(userInfoStr) : null);
const isAdmin = computed(() => currentUser.value?.roleName === '超级管理员');
const isAdvancedLibraryAdmin = computed(() => {
  if (isAdmin.value || isAdvancedLibraryAdmin.value) return false;
  if (!currentUser.value?.knowledgeBaseGroupRoleInfos) return true;
  return Object.entries(currentUser.value.knowledgeBaseGroupRoleInfos).some(
    ([groupId, roleId]) => groupId === props.groupId && roleId === 6
  );
});
const isAssignRole = computed(() => {
  if (isAdmin.value || isAdvancedLibraryAdmin.value) return false;
  if (!currentUser.value?.knowledgeBaseGroupRoleInfos) return true;
  return Object.entries(currentUser.value.knowledgeBaseGroupRoleInfos).some(
    ([groupId, roleId]) => groupId === props.groupId && roleId === 11
  );
});

const props = defineProps<{
  show: boolean;
  groupId: string;
}>();

const emit = defineEmits<{
  (e: 'close'): void;
  (e: 'role-updated'): void;
}>();

// 新增状态
const showAllUsers = ref(false);
const allUsers = ref<User[]>([]);
const allUsersSearchQuery = ref('');
const currentGroupType = ref<'admin' | 'viewer' | 'editor' | 'assigner' | null>(null);

// 过滤所有用户
const filteredAllUsers = computed(() => {
  if (!currentGroupType.value) return [];
  
  // 获取当前权限组（如管理员、可查看用户等）中已选中的用户列表
  const selectedArray = {
    admin: selectedAdminUsers,
    viewer: selectedViewerUsers,
    editor: selectedEditorUsers,
    assigner: selectedAssignerUsers,
  }[currentGroupType.value].value;
  
  // 过滤掉已在当前权限组中的用户，并匹配搜索条件
  const filteredUsers = allUsers.value.filter(user => {
    if (!user.nickname) return false;
    
    const isInCurrentGroup = selectedArray.includes(user.id);
    const matchesSearch = user.nickname.toLowerCase().includes(allUsersSearchQuery.value.toLowerCase());
    
    if (isInCurrentGroup) {
      console.log(`用户 ${user.id} (${user.nickname}) 已在当前权限组中，将被过滤掉`);
    }
    
    return !isInCurrentGroup && matchesSearch;
  });
  
  console.log('过滤后的用户列表:', filteredUsers.map(user => user.id));
  return filteredUsers;
});

// 加载所有用户
const fetchAllUsers = async () => {
  try {
    const url = new URL(`${API_CONFIG.BASE_URL}/user/page`);
    url.searchParams.append('pageNo', `${currentPage.value}`);
    url.searchParams.append('pageSize', `${pageSize.value}`);
    
    const response = await fetch(url, {
      method: 'GET',
      credentials: 'include'
    });
    
    const result = await response.json();
    if (result.code === "0") {
      allUsers.value = result.data.dataList;
    }
  } catch (error) {
    console.error('获取所有用户失败:', error);
  }
};

// 添加用户到当前权限组
const addUserToCurrentGroup = (userId: string) => {
  if (!currentGroupType.value) return;

  const currentGroupUsers = {
    admin: adminUsers,
    viewer: viewerUsers,
    editor: editorUsers,
    assigner: assignerUsers,
  }[currentGroupType.value];

  const selectedArray = {
    admin: selectedAdminUsers,
    viewer: selectedViewerUsers,
    editor: selectedEditorUsers,
    assigner: selectedAssignerUsers,
  }[currentGroupType.value];

  // 确保用户不在当前权限组中
  const user = allUsers.value.find(u => u.id === userId);
  if (user && !currentGroupUsers.value.some(u => u.id === userId)) {
    currentGroupUsers.value.push(user);
    if (!selectedArray.value.includes(userId)) {
      selectedArray.value.push(userId);
    }
    console.log(`用户 ${userId} 已添加到 ${currentGroupType.value} 组`);
  }
};

// 提交权限修改
const handleSubmit = async (type: 'admin' |'viewer' | 'editor' | 'assigner') => {
  try {
    if (!props.groupId) {
      ToastService.error('资料库组ID不能为空');
      return;
    }
    
    const selectedUsers = type === 'admin' ? selectedAdminUsers.value : type === 'viewer' ? selectedViewerUsers.value : type === 'editor' ? selectedEditorUsers.value : selectedAssignerUsers.value;
    const roleId = type === 'admin' ? 6 : type === 'viewer' ? 8 : type === 'editor' ? 7 : 11;
    
    const response = await fetch(`${API_CONFIG.BASE_URL}/knowledge-base-group/update-group-user`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      credentials: 'include',
      body: JSON.stringify({
        knowledgeBaseGroupId: props.groupId,
        userIds: selectedUsers,
        roleId
      })
    });
    
    const result = await response.json();
    if (result.code === "0") {
      ToastService.success('权限修改成功');
      emit('role-updated');
      // 重新获取所有用户列表数据
      await initGroupUsers();
    } else {
      ToastService.error(`修改失败: ${result.msg}`);
    }
  } catch (error) {
    console.error('修改权限失败:', error);
    ToastService.error('修改权限失败，请检查网络连接');
  }
};

// 设置当前权限组类型
const setCurrentGroupType = (type: 'admin' | 'viewer' | 'editor' | 'assigner') => {
  if (currentGroupType.value === type && showAllUsers.value) {
    // 如果已经是当前类型且显示中，则隐藏所有用户窗口，恢复其他窗口
    if (type === 'admin' || type === 'viewer' || type === 'editor' || type === 'assigner') {
      handleSubmit(type);
    }
    showAllUsers.value = false;
    currentGroupType.value = null;
  } else {
    // 否则显示所有用户窗口，并设置当前类型
    currentGroupType.value = type;
    showAllUsers.value = true;
    if (allUsers.value.length === 0) {
      fetchAllUsers();
    }
  }
};

onMounted(() => {
  initGroupUsers();
});

// 不同权限的用户列表
const adminUsers = ref<User[]>([]);
const currentPage = ref(1);
const pageSize = ref(100000);

const fetchGroupUsers = async (roleId: number, targetUsers: Ref<User[]>, selectedUsers: Ref<string[]>) => {
  try {
    const url = new URL(`${API_CONFIG.BASE_URL}/knowledge-base-group/page/group-user`);
    url.searchParams.append('pageNo', `${currentPage.value}`);
    url.searchParams.append('pageSize', `${pageSize.value}`);
    url.searchParams.append('roleId', `${roleId}`);
    url.searchParams.append('knowledgeBaseGroupId', props.groupId);
    
    const response = await fetch(url, {
      method: 'GET',
      credentials: 'include'
    });
    
    const result = await response.json();
    if (result.code === "0") {
      targetUsers.value = result.data.dataList.map((user: KnowledgeBaseGroupUserRsp) => ({
        id: user.userId.toString(),
        nickname: user.nickname,
        roleId: user.roleId
      }));
      // 初始化选中用户列表
      selectedUsers.value = targetUsers.value.map(user => user.id);
    } else if (result.code === '0001') {
      emit('close');
    }
  } catch (error) {
    console.error(`获取权限组用户失败 (roleId: ${roleId}):`, error);
  }
};

// 初始化不同权限组的用户数据
const initGroupUsers = async () => {
  try {
    await Promise.all([
      fetchGroupUsers(6, adminUsers, selectedAdminUsers),
      fetchGroupUsers(8, viewerUsers, selectedViewerUsers),
      fetchGroupUsers(7, editorUsers, selectedEditorUsers),
      fetchGroupUsers(11, assignerUsers, selectedAssignerUsers)
    ]);
  } catch (error) {
    console.error('初始化用户数据失败:', error);
  }
};
const viewerUsers = ref<User[]>([]);
const editorUsers = ref<User[]>([]);
const assignerUsers = ref<User[]>([]);

// 搜索查询
const adminSearchQuery = ref('');
const viewerSearchQuery = ref('');
const editorSearchQuery = ref('');
const assignerSearchQuery = ref('');

// 选中的用户
const selectedAdminUsers = ref<string[]>([]);
const selectedViewerUsers = ref<string[]>([]);
const selectedEditorUsers = ref<string[]>([]);
const selectedAssignerUsers = ref<string[]>([]);

// 过滤后的用户列表
const filteredAdminUsers = computed(() => {
  return adminUsers.value.filter(user => 
    user.nickname && user.nickname.toLowerCase().includes(adminSearchQuery.value.toLowerCase())
  );
});

const filteredViewerUsers = computed(() => {
  return viewerUsers.value.filter(user => 
    user.nickname && user.nickname.toLowerCase().includes(viewerSearchQuery.value.toLowerCase())
  );
});

const filteredEditorUsers = computed(() => {
  return editorUsers.value.filter(user => 
    user.nickname && user.nickname.toLowerCase().includes(editorSearchQuery.value.toLowerCase())
  );
});

const filteredAssignerUsers = computed(() => {
  return assignerUsers.value.filter(user => 
    user.nickname && user.nickname.toLowerCase().includes(assignerSearchQuery.value.toLowerCase())
  );
});

// 切换用户选择状态
const toggleUserSelection = (userId: string, type: 'admin' | 'viewer' | 'editor' | 'assigner') => {
  let selectedArray: string[];
  
  switch (type) {
    case 'admin':
      selectedArray = selectedAdminUsers.value;
      break;
    case 'viewer':
      selectedArray = selectedViewerUsers.value;
      break;
    case 'editor':
      selectedArray = selectedEditorUsers.value;
      break;
    case 'assigner':
      selectedArray = selectedAssignerUsers.value;
      break;
  }
  
  const index = selectedArray.indexOf(userId);
  if (index === -1) {
    selectedArray.push(userId);
  } else {
    selectedArray.splice(index, 1);
  }
};

// 从权限组中移除用户
const removeUserFromGroup = (userId: string, type: 'admin' | 'viewer' | 'editor' | 'assigner') => {
  const currentGroupUsers = {
    admin: adminUsers,
    viewer: viewerUsers,
    editor: editorUsers,
    assigner: assignerUsers,
  }[type];

  const selectedArray = {
    admin: selectedAdminUsers,
    viewer: selectedViewerUsers,
    editor: selectedEditorUsers,
    assigner: selectedAssignerUsers,
  }[type];

  // 从当前权限组中移除用户
  const userIndex = currentGroupUsers.value.findIndex(u => u.id === userId);
  if (userIndex !== -1) {
    currentGroupUsers.value.splice(userIndex, 1);
  }

  // 从选中列表中移除用户
  const selectedIndex = selectedArray.value.indexOf(userId);
  if (selectedIndex !== -1) {
    selectedArray.value.splice(selectedIndex, 1);
  }

  console.log(`用户 ${userId} 已从 ${type} 组中移除`);
};



</script>

<style scoped>
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.modal-content {
  background-color: white;
  border-radius: 8px;
  width: auto;
  max-width: 95%;
  max-height: 90vh;
  display: flex;
  flex-direction: column;
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 20px;
  border-bottom: 1px solid #e0e0e0;
}

.modal-header h3 {
  margin: 0;
  color: #333;
}

.close-btn {
  background: none;
  border: none;
  font-size: 24px;
  cursor: pointer;
  color: #999;
}

.modal-body {
  padding: 20px;
  overflow: auto;
  flex: 1;
  width: 100%;
}

.permissions-container {
  display: flex;
  gap: 16px;
  height: 500px;
  width: 100%;
  min-width: 100%;
  overflow-x: auto;
}

.permission-section {
  display: flex;
  flex-direction: column;
  border: 1px solid #e0e0e0;
  border-radius: 4px;
  overflow: hidden;
  min-width: 300px;
  flex-shrink: 0;
}

.permission-section h4 {
  margin: 0;
  padding: 10px;
  background-color: #f5f5f5;
  border-bottom: 1px solid #e0e0e0;
}

.search-box {
  padding: 10px;
  border-bottom: 1px solid #e0e0e0;
}

.search-input {
  width: 100%;
  padding: 8px;
  border: 1px solid #d9d9d9;
  border-radius: 4px;
}

.user-list {
  flex: 1;
  overflow-y: auto;
  padding: 10px;
}

.user-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px 12px;
  cursor: pointer;
  border-radius: 4px;
  margin-bottom: 4px;
}

.user-item:hover {
  background-color: #f5f5f5;
}

.user-item.selected {
  background-color: #e6f7ff;
  border: 1px solid #91d5ff;
}

.add-btn {
  background: #1890ff;
  color: white;
  border: none;
  padding: 4px 8px;
  border-radius: 4px;
  cursor: pointer;
  margin-left: 8px;
  font-size: 12px;
}

.action-btn {
  background: #52c41a;
  color: white;
  border: none;
  padding: 4px 8px;
  border-radius: 4px;
  cursor: pointer;
  font-size: 12px;
}

.remove-btn {
  background: #ff4d4f;
  color: white;
  border: none;
  padding: 4px 8px;
  border-radius: 4px;
  cursor: pointer;
  font-size: 12px;
  margin-left: 8px;
}

.user-name {
  flex: 1;
}

.user-role {
  font-size: 12px;
  color: #666;
  padding: 2px 6px;
  border-radius: 4px;
  background-color: #f0f0f0;
}

.empty-list {
  color: #999;
  text-align: center;
  padding: 20px;
}
</style>